<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header :to="'/geologicalDisaster'" :back="true" />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="`${provinceName}已有地震地质灾害数量`" />
          <!-- 统计 -->
          <disaster-number @getType="getType" />
        </div>
        <div class="app-left-item">
          <subheadings :name="`${provinceName}地震地质灾害发育数量图`" />
          <BarChart />
        </div>
        <div class="app-left-item">
          <subheadings :name="'地震地质灾害系统服务统计'" />
          <service-statistics />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="'地震地质灾害评估成果'" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '-30px', left: '42px' }" />
          <!-- <IndexMap></IndexMap> -->
          <OlMap
            ref="olmapRef"
            :showSouthSea="false"
            :blueChina="false"
            :doubleZoomDisable="true"
            :pinchZoomDisable="true"
            :refId="'geologicaldisaster1'"
            style="height: 100%"
            @getMap="getMap"
            @mapClick="mapClick"
          ></OlMap>
          <CustomMenu
            style="position: absolute; left: 42px; bottom: 140px"
            :options="menuOptions"
            @onOptionClick="handleOptionClick"
          />
          <ComLegend
            v-if="!hideComLegend"
            style="position: absolute; left: 42px; bottom: 220px"
            title="图例"
            subTitle=""
            :items="legendItems"
            :items-per-column="10"
          ></ComLegend>
          <p>
            <span style="position: absolute; top: 20px; right: 40px; font-size: 14px; color: #ffffff">{{
              radioShowLabel
            }}</span>
          </p>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item">
          <!-- 次级标题 -->
          <subheadings :name="'评估类型'" />
          <EvaluationType @getTypeValue="getTypeValue" />
        </div>
        <div class="app-right-item">
          <subheadings :name="`${provinceName}地震地质灾害概况`" />
          <DisasterOverview :typeData="paramsData" />
        </div>
        <div class="app-right-item">
          <subheadings :name="`${provinceName}危险性面积统计分析`" />
          <HazardousArea :typeData="paramsData" :provinceCode="code" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
// 引入 Element Plus 默认样式文件
import 'element-plus/theme-chalk/index.css';
//地图
// import IndexMap from '@/views/securityActivity/map/index.vue';
import DisasterNumber from './DisasterNumber.vue';
import DisasterOverview from './DisasterOverview.vue';
import ServiceStatistics from './ServiceStatistics.vue';
import EvaluationType from './EvaluationType.vue';
import BarChart from './BarChart.vue';
import HazardousArea from './HazardousArea.vue';

// 系统选择
import SystemSelect from '@/components/SystemSelect';
import { getActivityMap } from '@/api/securityActivity.js';
// start
import OlMap from '@/components/Olmap';
import { Style, Circle as CircleStyle, Fill, Stroke, Icon, Text } from 'ol/style';
import Feature from 'ol/Feature';
import { Point } from 'ol/geom';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';
import yellowMarkerImg from '@/assets/map/image/newImage/yelloMarker.png';
import CustomMenu from '@/components/CustomMenu';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import { ref } from 'vue';
import ComLegend from '@/components/ComLegend';
import { getChinaBaseMap, getGridLayer, getTiandituImgMap, getTiandituDemMap } from '@/map/projMap.js';
import { getTileLayerByCode, getProviceFeatureByCode } from '@/utils/matchProvince';
import { Util } from '@supermap/iclient-ol';
import { getMapDisaster,getResultLogisticGrowth } from '@/api/geologicalDisaster.js';
// end

const route = useRoute();
const { code, provinceName } = route.query;

const paramsData = ref();
// start
const mapInstance = ref(null);
const selectProvinceLayer = ref(null);
const tiandituImgLayer = ref(null);
const TiandituDemLayer = ref(null);
const vectorLayer = ref(null);
const hideComLegend = ref(false);

const olmapRef = ref(null);
const menuOptions = ['地图', '影像图', '地形图'];
const radioShowLabel = ref('');
const radioLabels = [
  { title: '设定地震', value: ['VI度', 'VII度', 'VIII度', 'IX度', 'X度', 'XI度'] },
  { title: '场地类别', value: ['活动构造区', '稳定大陆区'] },
  { title: '抗震设防烈度', value: ['7度', '8度', '9度'] },
  { magnitudeTitle: '震级范围', dateTitle: '时间范围' },
];
const quakeTypes = ['地震滑坡', '砂土液化', '软土震陷', '地表破裂带'];
const legendItems = ref([
  { label: '极低危险', color: 'rgba(118,183,74,1)', w: 10, h: 8, r: 0 },
  { label: '低危险', color: 'rgba(173,217,83,1)', w: 10, h: 8, r: 0 },
  { label: '中危险', color: 'rgba(255,253,97,1)', w: 10, h: 8, r: 0 },
  { label: '高危险', color: 'rgba(241,158,75,1)', w: 10, h: 8, r: 0 },
  { label: '极高危险', color: 'rgba(234,72,63,1)', w: 10, h: 8, r: 0 },
]);
// end

// start
const getMap = async (map) => {
  mapInstance.value = map.value;
  await createProviceLayer();
  createTiandiImgLayer();
  createTiandituDemLayer();
  // addProvinceNameLayer();
};
const createTiandituDemLayer = () => {
  TiandituDemLayer.value = getTiandituDemMap();
  mapInstance.value.addLayer(TiandituDemLayer.value);
  TiandituDemLayer.value.setVisible(false);
  TiandituDemLayer.value.set('id', 'china_demtu');
  TiandituDemLayer.value.setZIndex(0);
};
const createTiandiImgLayer = () => {
  tiandituImgLayer.value = getTiandituImgMap();
  mapInstance.value.addLayer(tiandituImgLayer.value);
  tiandituImgLayer.value.setVisible(false);
  tiandituImgLayer.value.set('id', 'china_tianditu');
  tiandituImgLayer.value.setZIndex(0);
};
const createProviceLayer = async () => {
  selectProvinceLayer.value = await getTileLayerByCode(code);
  selectProvinceLayer.value.setZIndex(0);
  mapInstance.value.addLayer(selectProvinceLayer.value);
  let proviceFeature = await getProviceFeatureByCode(code);
  const provinceExtent = proviceFeature.getGeometry().getExtent();
  // provinceExtent[1] = provinceExtent[1] - 2;
  mapInstance.value.getView().setCenter(proviceFeature.get('center'));
  mapInstance.value.getView().fit(provinceExtent, { padding: [20, 20, 250, 20], duration: 1000 }); // 1000毫秒的动画效果
};
const setMask = async (layer) => {
  let proviceFeature = await getProviceFeatureByCode(code);
  Util.setMask(layer, proviceFeature);
};
const unSetMask = async (layer) => {
  let proviceFeature = await getProviceFeatureByCode(code);
  Util.unsetMask(layer, proviceFeature);
};
const handleMenuButtonClick = (button) => {
  console.log('Button clicked:', button.label);
  // 在这里进行按钮点击后的逻辑处理
};
function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 3,
    style: function (feature) {
      const textstyle = new Style({
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#B2BEB5' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}

function setQuakeLayerVisible(layerId, flag) {
  let layers = mapInstance.value.getLayers();
  layers.forEach((layer) => {
    let lid = layer.get('id');
    if (lid) {
      if (lid.indexOf(layerId) != -1) {
        layer.setVisible(flag);
      }
    }
  });
}

function getQuakeLayerById(layerId) {
  let returnLayer;
  let layers = mapInstance.value.getLayers();
  layers.forEach((layer) => {
    if (layer.get('id') == layerId) {
      returnLayer = layer;
    }
  });

  return returnLayer;
}

function showQuakeLayer(urlType) {
  setQuakeLayerVisible('quake_level', false);

  let layerId = 'quake_level_' + urlType;
  let returnLayer = getQuakeLayerById(layerId);

  if (returnLayer) {
    setQuakeLayerVisible(layerId, true);
  } else {
    /*let pack = process.env.NODE_ENV === 'development';
    let url = pack
      ? '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1692611889384_' + urlType
      : '/iserver/services/map-demtif/rest/maps/逻辑斯蒂模型_计算_1693795938950_' + urlType;
    getGridLayer(url).then((layer) => {
      layer.set('id', layerId);
      mapInstance.value.addLayer(layer);
      setMask(layer);
    });*/
    try {
      //根据烈度类型获取大屏展示任务地震滑坡逻辑斯蒂计算结果并添加图层
      getResultLogisticGrowthByTYPE(urlType);
    } catch (error) {
      console.log(error);
    }
  }
}

//根据烈度类型获取地震滑坡逻辑斯蒂计算结果并添加图层
const getResultLogisticGrowthByTYPE = async (dzIntensity) => {
  let res = await getResultLogisticGrowth(dzIntensity);
  console.log(res);
  let data = res.data?res.data:[];
  if (data && data.length > 0) {
    data.forEach((item) => {
      let taskId = item.taskId;
      let filePath = item.filePath;
      let url = '/iserver/services/map-demtif/rest/maps/' + filePath;
      let layerId = 'dzhp_level_' + dzIntensity + "_" + taskId;
      console.log(layerId+","+url);
      getGridLayer(url).then((layer) => {
        layer.set('id', layerId);
        mapInstance.value.addLayer(layer);
        setMask(layer);//图层掩膜
      });
    });
  }
};

const createVectorLayer = () => {
  vectorLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 2,
  });
  mapInstance.value.addLayer(vectorLayer.value);
};
const addRandomPoints = async (type) => {
  if (!vectorLayer.value) {
    return;
  }
  let res = await getMapDisaster({ type, code });
  let data = res.data?.list;
  if (data && data.length > 0) {
    data.forEach((item) => {
      const point = new Feature({
        geometry: new Point([item.lon, item.lat]),
      });
      const style = new Style({
        image: new Icon({
          src: yellowMarkerImg, // 图片路径
          scale: 1, // 图片缩放比例
        }),
        text: new Text({
          text: item.num.toString(), // 将数字转换为字符串显示
          offsetY: -5, // 调整数字在图标上方的位置
          fill: new Fill({ color: 'rgba(5, 4, 38, 1)' }),
          font: 'normal 13px Arial', // 设置字体样式
        }),
      });
      point.setStyle(style);
      vectorLayer.value.getSource().addFeature(point);
    });
  }
};
const handleOptionClick = (option, index) => {
  console.log(`Selected option in parent component: ${option}----${index}`);
  // 在这里处理选项点击事件，例如执行特定操作或更新数据
  if (index == 0) {
    selectProvinceLayer.value.setVisible(true);
    tiandituImgLayer.value.setVisible(false);
    TiandituDemLayer.value.setVisible(false);
  } else if (index == 1) {
    selectProvinceLayer.value.setVisible(false);
    tiandituImgLayer.value.setVisible(true);
    TiandituDemLayer.value.setVisible(false);
    setMask(tiandituImgLayer.value);
  } else if (index == 2) {
    selectProvinceLayer.value.setVisible(false);
    tiandituImgLayer.value.setVisible(false);
    TiandituDemLayer.value.setVisible(true);
    setMask(TiandituDemLayer.value);
  }
};
// end

const getType = (params) => {
  hideComLegend.value = true;

  radioShowLabel.value = quakeTypes[params - 1];

  if (vectorLayer.value) {
    mapInstance.value.removeLayer(vectorLayer.value);
  }

  setQuakeLayerVisible('quake_level', false);
  createVectorLayer();
  addRandomPoints(params);
};

const getTypeValue = (params) => {
  paramsData.value = params;
  hideComLegend.value = false;
  if (vectorLayer.value) {
    mapInstance.value.removeLayer(vectorLayer.value);
  }

  if (params.parentType == 4) {
    let index1 = params.parentType - 1;
    let label1 = radioLabels[index1].magnitudeTitle;
    let label2 = radioLabels[index1].dateTitle;
    if (
      params.magnitudeRange1 != '' &&
      params.magnitudeRange2 != '' &&
      params.dateRange1 != '' &&
      params.dateRange2 != ''
    ) {
      radioShowLabel.value =
        label1 +
        '：' +
        params.magnitudeRange1 +
        '-' +
        params.magnitudeRange2 +
        '，' +
        label2 +
        '：' +
        params.dateRange1 +
        '-' +
        params.dateRange2;
    } else if (
      params.dateRange1 != '' &&
      params.dateRange2 != '' &&
      (params.magnitudeRange1 == '' || params.magnitudeRange2 == '')
    ) {
      radioShowLabel.value = label2 + '：' + params.dateRange1 + '-' + params.dateRange2;
    } else if (
      params.magnitudeRange1 != '' &&
      params.magnitudeRange2 != '' &&
      (params.dateRange1 == '' || params.dateRange2 == '')
    ) {
      radioShowLabel.value = label1 + '：' + params.magnitudeRange1 + '-' + params.magnitudeRange2;
    } else {
      radioShowLabel.value = '';
    }
  } else {
    let index1 = params.parentType - 1;
    let index2 = params.childType - 1;
    let label1 = radioLabels[index1].title;
    let label2 = radioLabels[index1].value[index2];
    radioShowLabel.value = label1 + '：' + label2;
  }

  if (params.parentType == 1) {
    //加载地震地图图层
    let type = params.childType + 5;
    showQuakeLayer(type);

    legendItems.value = [
      { label: '极低危险', color: 'rgba(118,183,74,1)', w: 10, h: 8, r: 0 },
      { label: '低危险', color: 'rgba(173,217,83,1)', w: 10, h: 8, r: 0 },
      { label: '中危险', color: 'rgba(255,253,97,1)', w: 10, h: 8, r: 0 },
      { label: '高危险', color: 'rgba(241,158,75,1)', w: 10, h: 8, r: 0 },
      { label: '极高危险', color: 'rgba(234,72,63,1)', w: 10, h: 8, r: 0 },
    ];
  } else if (params.parentType == 2) {
    setQuakeLayerVisible('quake_level', false);
    legendItems.value = [
      { label: '极低危险', color: 'rgba(118,183,74,1)', w: 10, h: 8, r: 0 },
      { label: '低危险', color: 'rgba(173,217,83,1)', w: 10, h: 8, r: 0 },
      { label: '中危险', color: 'rgba(255,253,97,1)', w: 10, h: 8, r: 0 },
      { label: '高危险', color: 'rgba(241,158,75,1)', w: 10, h: 8, r: 0 },
      { label: '极高危险', color: 'rgba(234,72,63,1)', w: 10, h: 8, r: 0 },
    ];
  } else if (params.parentType == 3) {
    setQuakeLayerVisible('quake_level', false);
    legendItems.value = [
      { label: '不震陷', color: 'rgba(118,183,74,1)', w: 10, h: 8, r: 0 },
      { label: '震陷', color: 'rgba(241,158,75,1)', w: 10, h: 8, r: 0 },
    ];
  } else if (params.parentType == 4) {
    setQuakeLayerVisible('quake_level', false);
    legendItems.value = [
      { label: '地表破裂带', color: 'rgba(234,64,53,1)', w: 10, h: 2, r: 0 },
      { label: '震中', color: 'rgba(234,64,53,1)', w: 10, h: 10, r: 50 },
    ];
  } else {
  }
};
</script>

<style scoped lang="scss">
.app-container {
  min-height: 1080px;
}
.app-main {
  display: flex;
  justify-content: space-between;
  .app-left {
    margin-left: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 450px;
    &-item {
      width: 450px;
      // background: linear-gradient(135deg, #00032D 0%, #000C58 50%, #00032D 100%);
      // opacity: .85;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
      }
      &:nth-child(1) {
        height: 280px;
      }
      &:nth-child(2) {
        height: 280px;
      }
      &:nth-child(3) {
        height: 300px;
      }
    }
  }

  .app-map {
    width: 960px;
    height: 100%;
    overflow: visible;
  }
  .app-right {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 450px;

    &-item {
      width: 450px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        /*position: static;*/
      }
      &:nth-child(1) {
        height: 180px;
      }
      &:nth-child(2) {
        height: 500px;
        z-index: 9;
      }
      &:nth-child(3) {
        z-index: 9;
        &::after {
          content: '';
          display: block;
          width: 450px;
          height: 20px;
          background-size: 100% 100%;
          background-image: url('../../assets/images/common/bg_bottom.png') !important;
          position: static;
        }
      }
    }
  }
}
</style>
